<?php

namespace app\admin\controller;


use app\admin\model\Role;
use app\admin\model\Role_node;
use app\admin\model\User;
use app\admin\model\User_role;
use think\Request;
use think\Paginator;
use app\admin\controller\Base;

class Users extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {

        $where = function($query){
            $query->field('password',true);
        };
        $list = User::all($where);

        return view('user/index', ['data'=>$list]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $list = Role::all();
        $data = [];
        foreach ($list as $val){
            $data[] = $val->getData();
        }
        return view('user/add', ['data'=>$data]);

    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $info = input('post.');
        $info['password'] = md5($info['password']);
        $user['username'] = $info['username'];
        $user['email'] = $info['email'];
        $user['tel'] = $info['tel'];
        $user['password'] = $info['password'];
        $result = User::create($user)->getData()['id'];

        $user_role = new User_role();
        $user_role->add($info['role'],$result);
        $data = [];
        //判断
        if ($result>0){
           $data['status'] = true;
           $data['message'] = '添加成功';
        }else{
            $data['status'] = false;
            $data['message'] = '添加失败';
        }
        return json($data);
    }



    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $data = input('put.');
        $user = User::get($id);
        if($data['password'] !== ''){
            $data['password'] = md5($data['password']);
            $user->password = $data['password'];
        }
        $user->status = $data['status'];
        $result = $user->save();
        $data = [];
        if ($result>0){
            $data['status'] = true;
            $data['message'] = '添加成功';
        }else{
            $data['status'] = false;
            $data['message'] = '添加失败';
        }
        return json($data);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $user =  User::get($id);
        $result = $user->delete();
        User_role::where('uid', '=', $id)->delete();
        $data = [];
        if ($result>0){
            $data['status'] = true;
            $data['message'] = '删除成功';
        }else{
            $data['status'] = false;
            $data['message'] = '删除失败';
        }
        return json($data);
    }
}
